package com.fndsoft.police.xuancheng.util;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class GsonUtils {

	/**
	 * 获取java.util.Date日期解析Gson对象
	 * @author liujiaqi
	 * @creation time 2014-3-25下午12:03:31
	 * @version
	 * @return
	 */
	public static Gson getUtilDateGson() {
		return new GsonBuilder()
				.registerTypeAdapter(Date.class, new UtilDateSerializer())
				.setPrettyPrinting().create();
	}

	/**
	 * 实现所有的在转换规则
	 * 
	 * @author liujiaqi
	 * @creation time 2014-3-25下午2:34:32
	 * @version
	 * @return
	 */
	public static Gson getCommonGson() {
		return new GsonBuilder()
				.registerTypeAdapter(Date.class, new UtilDateSerializer())
				.setPrettyPrinting()
				.create();
	}
	
	
	/**
	 * java.util.Date日期解析适配器
	 * @author liujiaqi
	 * @creationTime 2014-3-25下午12:03:04
	 * @version 
	 *
	 */
	private static class UtilDateSerializer implements JsonSerializer<Date>,
			JsonDeserializer<Date> {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
				Locale.getDefault());

		@Override
		public JsonElement serialize(Date date, Type type,
				JsonSerializationContext context) {
			String value = sdf.format(date);
			return new JsonPrimitive(value);
		}

		@Override
		public Date deserialize(JsonElement arg0, Type arg1,
				JsonDeserializationContext arg2) throws JsonParseException {
			String dateStr = arg0.getAsString();
			Date value = null;
			try {
				value = sdf.parse(dateStr);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			return value;
		}
	}
}
